<template>
    <div class="product-order-list-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-content">
                    <div class="search-left">
                        <el-form :model="searchForm" :inline="true" class="search-form">
                            <el-form-item label="订单号:">
                                <el-input 
                                    v-model="searchForm.orderNo" 
                                    placeholder="输入订单号" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="会员姓名:">
                                <el-input 
                                    v-model="searchForm.memberName" 
                                    placeholder="输入会员姓名" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="会员手机:">
                                <el-input 
                                    v-model="searchForm.memberPhone" 
                                    placeholder="输入会员手机" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="订单状态:">
                                <el-select 
                                    v-model="searchForm.orderStatus" 
                                    placeholder="请选择" 
                                    clearable
                                    style="width: 150px"
                                >
                                    <el-option label="待付款" :value="0" />
                                    <el-option label="已付款" :value="1" />
                                    <el-option label="已发货" :value="2" />
                                    <el-option label="已送达" :value="3" />
                                    <el-option label="已完成" :value="4" />
                                    <el-option label="已取消" :value="5" />
                                    <el-option label="退款中" :value="6" />
                                    <el-option label="已退款" :value="7" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="支付状态:">
                                <el-select 
                                    v-model="searchForm.paymentStatus" 
                                    placeholder="请选择" 
                                    clearable
                                    style="width: 150px"
                                >
                                    <el-option label="未支付" :value="0" />
                                    <el-option label="已支付" :value="1" />
                                    <el-option label="支付失败" :value="2" />
                                    <el-option label="已退款" :value="3" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="语言:">
                                <el-select 
                                    v-model="searchForm.language" 
                                    placeholder="请选择" 
                                    clearable
                                    style="width: 150px"
                                >
                                    <el-option label="中文" value="zh" />
                                    <el-option label="英文" value="en" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="创建时间:">
                                <el-date-picker
                                    v-model="searchForm.startTime"
                                    type="date"
                                    placeholder="开始日期"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    style="width: 150px"
                                />
                            </el-form-item>
                            <el-form-item label="至:">
                                <el-date-picker
                                    v-model="searchForm.endTime"
                                    type="date"
                                    placeholder="结束日期"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                                    style="width: 150px"
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="search-right">
                        <el-button type="primary" @click="handleSearch">查询结果</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="orderNo" label="订单号" width="180" />
                    <el-table-column prop="memberName" label="会员姓名" width="120" />
                    <el-table-column prop="memberPhone" label="会员手机" width="140" />
                    <el-table-column prop="productName" label="商品名称" width="200" />
                    <el-table-column prop="quantity" label="购买数量" width="100" align="center" />
                    <el-table-column prop="payAmount" label="支付金额" width="120" align="right">
                        <template #default="{ row }">
                            ¥{{ row.payAmount }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="orderStatusName" label="订单状态" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag 
                                :type="getOrderStatusType(row.orderStatus)"
                                size="small"
                            >
                                {{ row.orderStatusName }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="paymentStatusName" label="支付状态" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag 
                                :type="getPaymentStatusType(row.paymentStatus)"
                                size="small"
                            >
                                {{ row.paymentStatusName }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatTime(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button 
                                v-if="row.orderStatus === 1" 
                                type="success" 
                                size="small" 
                                @click="handleShip(row)"
                            >
                                发货
                            </el-button>
                            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        <span>总共{{ pagination.total }}条记录,当前在第{{ pagination.current }}页</span>
                    </div>
                    <el-pagination
                        v-model:current-page="pagination.current"
                        :page-size="pagination.size"
                        :total="pagination.total"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="prev, pager, next, jumper"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                    />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ProductOrder, ProductOrderQueryParams } from '@/types/productOrder';
import { getProductOrderPage } from '@/api/order/product-order';
import { formatTime } from '@/utils/time';

const router = useRouter();

// 搜索表单
const searchForm = reactive({
    orderNo: '',
    memberName: '',
    memberPhone: '',
    orderStatus: undefined as number | undefined,
    paymentStatus: undefined as number | undefined,
    language: '',
    startTime: '',
    endTime: ''
});

// 表格数据
const loading = ref(false);
const tableData = ref<ProductOrder[]>([]);

// 分页数据
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
});

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
    switch (status) {
        case 0: // 待付款
            return 'warning';
        case 1: // 已付款
            return 'info';
        case 2: // 已发货
            return 'primary';
        case 3: // 已送达
            return 'success';
        case 4: // 已完成
            return 'success';
        case 5: // 已取消
            return 'danger';
        case 6: // 退款中
            return 'warning';
        case 7: // 已退款
            return 'danger';
        default:
            return 'info';
    }
};

// 获取支付状态类型
const getPaymentStatusType = (status: number) => {
    switch (status) {
        case 0: // 未支付
            return 'warning';
        case 1: // 已支付
            return 'success';
        case 2: // 支付失败
            return 'danger';
        case 3: // 已退款
            return 'danger';
        default:
            return 'info';
    }
};


// 获取商品订单列表数据
const getData = async () => {
    loading.value = true;
    try {
        const params: ProductOrderQueryParams = {
            current: pagination.current,
            size: pagination.size,
            ...(searchForm.orderNo && { orderNo: searchForm.orderNo }),
            ...(searchForm.memberName && { memberName: searchForm.memberName }),
            ...(searchForm.memberPhone && { memberPhone: searchForm.memberPhone }),
            ...(searchForm.orderStatus !== undefined && { orderStatus: searchForm.orderStatus }),
            ...(searchForm.paymentStatus !== undefined && { paymentStatus: searchForm.paymentStatus }),
            ...(searchForm.language && { language: searchForm.language }),
            ...(searchForm.startTime && { startTime: searchForm.startTime }),
            ...(searchForm.endTime && { endTime: searchForm.endTime })
        };
        
        console.log('请求参数:', params);
        
        const res = await getProductOrderPage(params);
        console.log('API响应:', res);
        
        const responseData = res as any;
        if (responseData && responseData.code === 200 && responseData.data) {
            tableData.value = responseData.data.records || responseData.data.list || [];
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0;
        } else {
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取商品订单数据失败';
            ElMessage.error(errorMsg);
            tableData.value = [];
            pagination.total = 0;
        }
    } catch (error) {
        console.error('获取商品订单数据失败:', error);
        ElMessage.error('网络错误，请稍后重试');
        tableData.value = [];
        pagination.total = 0;
    } finally {
        loading.value = false;
    }
};

// 搜索方法
const handleSearch = () => {
    pagination.current = 1;
    getData();
};

// 重置搜索
const handleReset = () => {
    searchForm.orderNo = '';
    searchForm.memberName = '';
    searchForm.memberPhone = '';
    searchForm.orderStatus = undefined;
    searchForm.paymentStatus = undefined;
    searchForm.language = '';
    searchForm.startTime = '';
    searchForm.endTime = '';
    pagination.current = 1;
    getData();
};

// 分页方法
const handlePageChange = (page: number) => {
    pagination.current = page;
    getData();
};

const handleSizeChange = (size: number) => {
    pagination.size = size;
    pagination.current = 1;
    getData();
};

// 查看订单详情
const handleView = (row: ProductOrder) => {
    router.push(`/product-order-detail/${row.id}`);
};

// 发货操作
const handleShip = (row: ProductOrder) => {
    ElMessageBox.confirm(
        `确定要发货订单 "${row.orderNo}" 吗？`,
        '发货确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        ElMessage.success('发货成功');
        // 这里可以调用发货API
        // 更新订单状态为"已发货"
        row.orderStatus = 2;
        row.orderStatusName = '已发货';
    }).catch(() => {
        ElMessage.info('已取消操作');
    });
};

// 页面初始化
onMounted(() => {
    getData();
});
</script>

<style scoped>
.product-order-list-container {
    padding: 20px;
}

/* 搜索区域 */
.search-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 8px;
}

.search-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-form {
    margin: 0;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.search-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 表格区域 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

/* 分页区域 */
.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    gap: 20px;
    align-items: center;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .product-order-list-container {
        padding: 10px;
    }
    
    .search-content {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }
    
    .search-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }
    
    .pagination-content {
        flex-direction: column;
        gap: 15px;
        align-items: center;
    }
}
</style>
